package com.zsck.pos.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.node.BaseNode;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.chinaums.commoncheck.R;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.jeremyliao.liveeventbus.core.LiveEvent;
import com.zsck.pos.activity.multiBill.MultiContract;
import com.zsck.pos.activity.multiBill.MultiPresenter;
import com.zsck.pos.adapter.MultiBillsAdapter;
import com.zsck.pos.base.MVPBaseActivity;
import com.zsck.pos.bean.BatchBills;
import com.zsck.pos.bean.CountingEvent;
import com.zsck.pos.bean.FeeEvent;
import com.zsck.pos.bean.FeeVOListBean;
import com.zsck.pos.bean.MonthBill;
import com.zsck.pos.bean.MultiBills;
import com.zsck.pos.bean.Project;
import com.zsck.pos.bean.SecondLiveEvent;
import com.zsck.pos.utils.LogUtil;
import com.zsck.pos.utils.SharePreferenceUtils;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MultiBillsActivity extends MVPBaseActivity<MultiPresenter> implements MultiContract.View {


    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.cb_all_select)
    CheckBox cbAllSelect;
    @BindView(R.id.tv_total_fee)
    TextView tvTotalFee;
    @BindView(R.id.btn_next)
    Button btnNext;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.tv_total_room)
    TextView tvTotalRoom;
    @BindView(R.id.tv_total_month)
    TextView tvTotalMonth;
    private MultiBillsAdapter multiBillsAdapter = new MultiBillsAdapter();

    private int currentPage = 1;
    private int pageSize = 10;
    private String condition;//搜索内容
    private String collectionObjId;//缴费类型2企业,1个人
    private String beginMonth;//开始月份
    private String endMonth;//结束月份
    private List<BaseNode> mFirstNode = new ArrayList<>();

    private Project mProject;
    //是否全选，
    private boolean isALLCHECK = false;
    //选择的费项
    private List<FeeVOListBean> userCheckFee = new ArrayList<>();
    private String contractNo;

    @Override
    protected MultiPresenter createPresenter() {
        return new MultiPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_multi_de_layout;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initView();
        initLoadMore();
        initData();
        initEvent();
    }

    private int curRoom=0;
    private int curMonth=0;
    private void initEvent() {

        LiveEventBus.get(CountingEvent.class).observe(this, new Observer<CountingEvent>() {
            @Override
            public void onChanged(CountingEvent monthNumEvent) {
                List<BaseNode> data = multiBillsAdapter.getData();
                curRoom=0;
                curMonth=0;
                for(BaseNode baseNode :data){
                    if(baseNode instanceof  BatchBills){
                        BatchBills batchBills= (BatchBills) baseNode;
                        if(batchBills.isChose()){
                            curRoom=curRoom+1;
                        }

                    }else if(baseNode instanceof  MonthBill){
                        MonthBill monthBill= (MonthBill) baseNode;
                        if(monthBill.isChecked()){
                            curMonth=curMonth+1;
                        }

                    }else if(baseNode instanceof  FeeVOListBean){

                    }
                }
                tvTotalMonth.setText(""+curMonth);
                tvTotalRoom.setText(""+curRoom);
            }
        });
        //二级菜单选择
        LiveEventBus.get(SecondLiveEvent.class)
                .observeForever(new Observer<SecondLiveEvent>() {
                    @Override
                    public void onChanged(SecondLiveEvent multiBillsEvent) {
                        MonthBill monthBill = multiBillsEvent.getMonthBill();

                        for (BatchBills batchBills : curBatchBills) {
                            List<MonthBill> monthBillList = batchBills.getMonthBillList();
                            for (int i = 0; i < monthBillList.size(); i++) {
                                MonthBill monthBill1 = monthBillList.get(i);
                                if (TextUtils.equals(monthBill1.getId(), monthBill.getId())) {
                                    monthBill1 = monthBill;
                                    monthBillList.set(i, monthBill1);
                                }
                            }
                            rvList.post(new Runnable() {
                                @Override
                                public void run() {
                                    multiBillsAdapter.nodeReplaceChildData(batchBills, monthBillList);
                                    multiBillsAdapter.notifyDataSetChanged();
                                }
                            });

                        }


                    }
                });

        LiveEventBus
                .get(FeeEvent.class)
                .observe(this, new Observer<FeeEvent>() {
                    @Override
                    public void onChanged(@Nullable FeeEvent event) {

                        FeeVOListBean feeVOListBean = event.getFeeVOListBean();

                        if (event.isADD()) {
                            billIdList.add(feeVOListBean.getBillId());
                            userCheckFee.add(feeVOListBean);
                            BigDecimal b1 = new BigDecimal(Double.toString(feeVOListBean.getAmount()));
                            BigDecimal b2 = new BigDecimal(Double.toString(totalFee));
                            totalFee = b1.add(b2).doubleValue();
                        } else {
                            billIdList.remove(feeVOListBean.getBillId());
                            userCheckFee.remove(feeVOListBean);
                            BigDecimal b1 = new BigDecimal(Double.toString(feeVOListBean.getAmount()));
                            BigDecimal b2 = new BigDecimal(Double.toString(totalFee));
                            totalFee = b2.subtract(b1).doubleValue();
                            feeVOListBeanMap.remove(feeVOListBean.getFeeId());
                        }

                        tvTotalFee.setText("¥" + totalFee + "元");
                        btnNext.setEnabled(totalFee > 0);
                    }
                });
    }

    private void initLoadMore() {
        multiBillsAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMore();
            }
        });
        multiBillsAdapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        multiBillsAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }


    private void loadMore() {
        currentPage++;
        if (mProject != null && mProject.getId() != null) {
            loadBillsList();
        }
    }

    private void initData() {
        Intent intent = getIntent();
        mProject = (Project) intent.getSerializableExtra("project");
        condition = intent.getStringExtra("condition");
        collectionObjId = intent.getStringExtra("collectionObjId");
        contractNo = intent.getStringExtra("contractNo");
        beginMonth = intent.getStringExtra("beginMonth");
        endMonth = intent.getStringExtra("endMonth");
//        SharePreferenceUtils.putString(this,"projectId",mProject.getId());
        if (mProject != null && mProject.getId() != null) {
//            SharePreferenceUtils.putString(this, "projectId", mProject.getId());
            loadBillsList();
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        refresh();
    }

    private void initView() {
        swipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        swipeLayout.setEnabled(false);
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                refresh();
//                swipeLayout.setRefreshing(false);
            }
        });
        rvList.setLayoutManager(new LinearLayoutManager(this));
        rvList.setAdapter(multiBillsAdapter);
        multiBillsAdapter.setDiffCallback(new DiffUtil.ItemCallback<BaseNode>() {
            @Override
            public boolean areItemsTheSame(@NonNull BaseNode oldItem, @NonNull BaseNode newItem) {
                return false;
            }

            @Override
            public boolean areContentsTheSame(@NonNull BaseNode oldItem, @NonNull BaseNode newItem) {
                return false;
            }
        });
        multiBillsAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                LogUtil.e("multiBillsAdapter", "multiBillsAdapter" + view.getId());
                multiBillsAdapter.notifyItemChanged(position);
            }
        });

        //全选
        cbAllSelect.setOnCheckedChangeListener(null);
        cbAllSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                billIdList.clear();
                userCheckFee.clear();
                totalFee = 0;
                curRoom=0;
                curMonth=0;
                for (BaseNode baseNode : mFirstNode) {

                    BatchBills batchBill = (BatchBills) baseNode;
                    batchBill.setChose(isChecked);
                    curRoom++;
                    List<MonthBill> monthBillList = batchBill.getMonthBillList();
                    for (MonthBill monthBill : monthBillList) {
                        curMonth++;
                        monthBill.setChecked(isChecked);
                        List<FeeVOListBean> feeVOList = monthBill.getFeeVOList();
                        for (FeeVOListBean feeVOListBean : feeVOList) {
                            feeVOListBean.setChecked(isChecked);
                            if (isChecked) {
                                billIdList.add(feeVOListBean.getBillId());
                                userCheckFee.add(feeVOListBean);
                            }
                            BigDecimal b1 = new BigDecimal(Double.toString(feeVOListBean.getAmount()));
                            BigDecimal b2 = new BigDecimal(Double.toString(totalFee));
                            totalFee = b1.add(b2).doubleValue();
                        }
                    }
                    multiBillsAdapter.nodeReplaceChildData(batchBill, monthBillList);
                }
                if (!isChecked) {
                    billIdList.clear();
                    userCheckFee.clear();
                    curMonth = 0;
                    curRoom = 0;
                    totalFee = 0;
                }
                multiBillsAdapter.notifyDataSetChanged();
                tvTotalRoom.setText(""+curRoom);
                tvTotalMonth.setText(""+curMonth);
                tvTotalFee.setText("￥" + totalFee + "元");
                btnNext.setEnabled(totalFee > 0);
            }
        });
    }

    private void refresh() {
        // 这里的作用是防止下拉刷新的时候还可以上拉加载
        cbAllSelect.setChecked(false);
        billIdList.clear();
        userCheckFee.clear();
        totalFee = 0;
        curRoom = 0;
        curMonth= 0;
        tvTotalFee.setText("");
        tvTotalRoom.setText("0");
        tvTotalMonth.setText("0");
        multiBillsAdapter.getLoadMoreModule().setEnableLoadMore(false);
        currentPage = 1;
        mFirstNode.clear();
        curBatchBills.clear();
        if (mProject != null) {
            loadBillsList();
        }



    }

    /*加载列表数据*/
    private void loadBillsList() {
        swipeLayout.setRefreshing(true);
        presenter.loadMultiBills(mProject.getId(), condition, collectionObjId, currentPage, pageSize
                , contractNo, beginMonth, endMonth);
    }


    @OnClick({R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_next:
                Intent intent = new Intent();
                ComponentName componentName = new ComponentName("com.ums.sz.pos", "com.zsck.pos.activity.PayActivity");
                intent.putExtra("amount", totalFee);
                intent.putExtra("projectId",mProject.getId());
                intent.putExtra("payer", userCheckFee.get(0).getCustomerName());
                intent.putExtra("billIdList", (Serializable) billIdList);
                intent.putExtra("multiFeeList", (Serializable) userCheckFee);
                intent.setComponent(componentName);
                startActivity(intent);
                break;
        }
    }

    private List<String> billIdList = new ArrayList<>();
    private Map<String, FeeVOListBean> feeVOListBeanMap = new HashMap<>();
    private double totalFee = 0.0d;
    private List<BatchBills> curBatchBills = new ArrayList<>();

    @Override
    public void loadBillsSuccess(MultiBills result) {
        swipeLayout.setRefreshing(false);
        if (result.getRows() != null && result.getTotal() > 0) {
            multiBillsAdapter.getLoadMoreModule().setEnableLoadMore(true);
            List<BatchBills> allNode = result.getRows();
            curBatchBills.addAll(result.getRows());
            for (int i = 0; i < allNode.size(); i++) {
                List<MonthBill> firstNode = allNode.get(i).getMonthBillList();
                List<BaseNode> secondNodeList = new ArrayList<>();
                for (int n = 0; n < firstNode.size(); n++) {
                    List<FeeVOListBean> feeVOList = firstNode.get(n).getFeeVOList();
                    //3层
                    List<BaseNode> thirdNodeList = new ArrayList<>();
                    for (FeeVOListBean feeVOListBean : feeVOList) {
                        feeVOListBean.setCusPosition(n);
                    }
                    thirdNodeList.addAll(feeVOList);
                    MonthBill monthBill = firstNode.get(n);
                    if (TextUtils.equals("1", monthBill.getBillType())) {
                        monthBill.setExpanded(true);
                    }
                    if (TextUtils.equals("returnRoom", monthBill.getSource()) || TextUtils.equals("returnRent", monthBill.getSource())) {
                        monthBill.setExpanded(true);
                    }
                    monthBill.setCurpos(i);
                    monthBill.setChildNode(thirdNodeList);
                    secondNodeList.add(monthBill);
                }
                BatchBills batchBills = allNode.get(i);
                batchBills.setChildNode(secondNodeList);
                batchBills.setExpanded(true);
                mFirstNode.add(batchBills);
                multiBillsAdapter.setList(mFirstNode);
                if (result.getTotal() < pageSize) {
                    //如果不够一页,显示没有更多数据布局
                    multiBillsAdapter.getLoadMoreModule().loadMoreEnd();
                } else {
                    multiBillsAdapter.getLoadMoreModule().loadMoreComplete();
                }

            }
        } else {
            if (currentPage == 1) {
                multiBillsAdapter.setEmptyView(getEmptyDataView());
            }else{
                multiBillsAdapter.getLoadMoreModule().loadMoreEnd();
            }
        }

    }

    private View getEmptyDataView() {
        View notDataView = getLayoutInflater().inflate(R.layout.empty_view, rvList, false);
        notDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                refresh();
            }
        });
        return notDataView;
    }

    @Override
    public void onFailure(String msg) {
        Toast.makeText(MultiBillsActivity.this, msg, Toast.LENGTH_SHORT).show();
        multiBillsAdapter.getLoadMoreModule().setEnableLoadMore(true);
        multiBillsAdapter.getLoadMoreModule().loadMoreFail();
        swipeLayout.setRefreshing(false);
    }
}
